//
//  AuctionViewController.m
//  MyNewProject
//
//  Created by 王春辉 on 2019/12/22.
//  Copyright © 2019年 sun. All rights reserved.
//

#import "AuctionViewController.h"
#import "AuctionCollectionViewDelegate.h"
#import "AuctionCollectionHeaderView.h"
#import "AuctionHallVC.h"
#import "AuctionSearchVC.h"
#import "AuctionTreasureVC.h"
#import "AuctionSoreShopVC.h"
#import "AuctionCouponVC.h"
#import "AuctionProductDetailVC.h"
#import "AuctionMessageVC.h"
#import "AuctionOrderListVC.h"
#import "StoreHomePageVC.h"
#import "XMJSWebViewController.h"
#import "ProductDetailVC.h"

#import "WJPasswordView.h"

#pragma mark -- mark 数据相关
#import "AuctionHomeBannerModel.h"
#import "AuctionHomeModel.h"
#import "AuctionSellModel.h"
#import "IndexNoticeModel.h"

#define MARGIN 15.0 // 左右边距

@interface AuctionViewController () {
    int _page;
    BOOL _firstLoad;
}
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) AuctionCollectionHeaderView *headerView;
@property (nonatomic, strong) AuctionCollectionViewDelegate *colletionViewDelegate;

#pragma mark -- mark CollectionViewBlock
@property (nonatomic, copy) AuctionCollectionViewShareButtonClickBlock shareBlock;
@property (nonatomic, copy) AuctionCollectionViewDidSelectAtRowIndexPathBlock selectBlock;

/// 倒计时结束回调
@property (nonatomic, copy) void(^collectionCountDownEndBlock)(void);

#pragma mark -- mark headerViewBlock
@property (nonatomic, copy) AuctionCollectionHeaderViewBannerClickBlock bannerBlock;
@property (nonatomic, copy) AuctionCollectionHeaderViewDetermineDetailClickBlock determineBlock;
@property (nonatomic, copy) AuctionCollectionHeaderViewBtnsClickBlock btnsBlock;
@property (nonatomic, copy) AuctionCollectionHeaderViewCouponButtonClickBlock couponBlock;
@property (nonatomic, copy) void(^couponsProductButtonClickBlock)(NSInteger);
@property (nonatomic, copy) AuctionCollectionHeaderViewRecommendMoreButtonClickBlock recommendMoreBlock;
@property (nonatomic, copy) AuctionCollectionHeaderViewRecommendSelectItemAtIndexPathBlock recommendSelectBlock;


@property (nonatomic, strong) AuctionHomeDataModel *homeDataModel;
@end

@implementation AuctionViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestContentData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"拍场";
    [self initBlock];
    [self initNavigationBar];
    [self initContentViews];
    _firstLoad = true;
}

/**
 初始化导航栏按钮
 */
- (void)initNavigationBar {
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    searchBtn.titleLabel.font = SKFONT_Medium(16);
    [searchBtn setTitleColor:SKColorWithHex(0xB1B1B1) forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"aution_search_btn_img"] forState:UIControlStateNormal];
    searchBtn.imageEdgeInsets = UIEdgeInsetsMake(searchBtn.imageEdgeInsets.top, MARGIN, searchBtn.imageEdgeInsets.bottom, searchBtn.imageEdgeInsets.right - MARGIN);
    searchBtn.titleEdgeInsets = UIEdgeInsetsMake(searchBtn.titleEdgeInsets.top, searchBtn.titleEdgeInsets.left + MARGIN, searchBtn.titleEdgeInsets.bottom, searchBtn.titleEdgeInsets.right - MARGIN);
    [searchBtn addTarget:self action:@selector(searchBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
    self.gk_navLeftBarButtonItem = searchBarItem;
    
    UIButton *messageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [messageBtn setImage:[UIImage imageNamed:@"aution_messge_btn_img"] forState:UIControlStateNormal];
    [messageBtn addTarget:self action:@selector(messageBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *messageBarBtn = [[UIBarButtonItem alloc] initWithCustomView:messageBtn];
    self.gk_navRightBarButtonItem = messageBarBtn;
}

/**
 初始化colletionView
 */
- (void)initContentViews {
    [self.collectionView addSubview:self.headerView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.mas_offset(SKTopBar_Height);
    }];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.width.mas_equalTo(self.view);
        make.top.mas_offset(0);
    }];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestContentData)];
}
#pragma mark -- mark 懒加载
- (AuctionCollectionHeaderView *)headerView {
    if (!_headerView) {
        self.headerView = [[AuctionCollectionHeaderView alloc] init];
        [_headerView bannerClickBlock:self.bannerBlock];
        [_headerView determineDetailClickBlock:self.determineBlock];
        [_headerView headerButtonsClickBlock:self.btnsBlock];
        [_headerView couponsButtonClickBlock:self.couponBlock];
        [_headerView couponsProductButtonClickBlock:self.couponsProductButtonClickBlock];
        [_headerView recommendMoreButtonClickBlock:self.recommendMoreBlock];
        [_headerView recommendSelectAtItemIndexPathBlock:self.recommendSelectBlock];
    }
    return _headerView;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        CGFloat centerMargin = 5.0; // 中间边距
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat item_w = (self.view.width - MARGIN * 2 - centerMargin) * 0.5;
        CGFloat item_h = item_w / 170.0 * 228.0;
        layout.itemSize = CGSizeMake(item_w, item_h);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 5;
        layout.minimumInteritemSpacing = 5;
        layout.sectionInset = UIEdgeInsetsMake(20, MARGIN, MARGIN, MARGIN);
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        [_collectionView registerClass:[AuctionCollectionViewCell class] forCellWithReuseIdentifier:@"auction_cell_identifier"];
        _collectionView.delegate = self.colletionViewDelegate;
        _collectionView.dataSource = self.colletionViewDelegate;
        _collectionView.showsHorizontalScrollIndicator = false;
        _collectionView.backgroundColor = SKColorWithHex(0xF7F7F7);
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
- (AuctionCollectionViewDelegate *)colletionViewDelegate {
    if (!_colletionViewDelegate) {
        self.colletionViewDelegate = [[AuctionCollectionViewDelegate alloc] init];
        _colletionViewDelegate.headerView = self.headerView;
        [_colletionViewDelegate shareButtonClockBlock:self.shareBlock];
        [_colletionViewDelegate didSelectItemAtIndexPathBlock:self.selectBlock];
        _colletionViewDelegate.countDownEndBlock = self.collectionCountDownEndBlock;
    }
    return _colletionViewDelegate;
}

#pragma mark -- mark 业务逻辑


#pragma mark -- mark 网络请求

/**
 获取网络数据
 */
- (void)requestContentData {
    [self requestBannersData];
    [self requestAuctionHomeData];
    [self requestAuctionRecommandShopData];
}

/**
 获取轮播图
 */
- (void)requestBannersData {
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Index/getBanner" params:@{} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        AuctionHomeBannerModel *model = [AuctionHomeBannerModel modelWithDictionary:response];
        if ([model isSuccess]) {
            NSMutableArray *mArr = [NSMutableArray<NSString *> arrayWithCapacity:model.data.count];
            for (AuctionBannerModel *bannerModel in model.data) {
                if ([bannerModel.is_show isEqualToString:@"1"]) {
                    [mArr addObject:bannerModel.imgurl];
                }
            }
            weakSelf.headerView.bannerImageNames = [NSArray arrayWithArray:mArr];
        }
    } failBlock:^(NSError *error) {
        
    }];
}

/**
 获取首页数据
 */
- (void)requestAuctionHomeData {
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Index/getIndex" params:@{} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        AuctionHomeModel *model = [AuctionHomeModel modelWithDictionary:response];
        if ([model isSuccess]) {
            [weakSelf reloadAuctionViewWith:model];
        }else {
            [weakSelf showMessage:model.msg];
        }
        [weakSelf endRefreshing];
    } failBlock:^(NSError *error) {
        [weakSelf endRefreshing];
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}

/**
 热门推荐拍卖
 */
- (void)requestAuctionRecommandShopData {
    _page = 1;
    SKWeakSelf;
    [self requestAuctionRecommandShopDataWith:_page Complete:^(AuctionSellModel *model) {
        weakSelf.colletionViewDelegate.dataArray = model.data;
        [weakSelf.collectionView reloadData];
    }];
}

- (void)requestMoreAuctionRecommandShopData {
    _page += 1;
    [self requestAuctionRecommandShopDataWith:_page Complete:^(AuctionSellModel *model) {
        
    }];
}

/**
 获取热门推荐数据

 @param page page
 @param complete 回调
 */
- (void)requestAuctionRecommandShopDataWith:(int)page Complete:(void(^)(id))complete {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param addEntriesFromDictionary:@{@"is_hot":@(1)}]; // 1 热门 0 全部
    [param addEntriesFromDictionary:@{@"page":@(page)}];
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Index/getSellList" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        AuctionSellModel *model = [AuctionSellModel modelWithDictionary:response];
        if ([model isSuccess]) {
            if (complete) {
                complete(model); }
        }else {
            
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}

- (void)endRefreshing {
    if ([self.collectionView.mj_header isRefreshing]) {
        [self.collectionView.mj_header endRefreshing];
    }
    if ([self.collectionView.mj_footer isRefreshing]) {
        [self.collectionView.mj_footer endRefreshing];
    }
}
#pragma mark -- mark EVENT

/**
 搜索

 @param sender sender
 */
- (void)searchBarButtonClick:(UIButton *)sender {
    AuctionSearchVC *vc = [[AuctionSearchVC alloc] init];
    vc.viewController = self;
    [self presentViewController:vc animated:true completion:nil];
}

/**
 消息中心

 @param sender sender
 */
- (void)messageBarButtonClick:(UIButton *)sender {
    AuctionMessageVC *vc = [[AuctionMessageVC alloc] init];
    [self.navigationController pushViewController:vc animated:true];
}

#pragma mark -- mark 业务逻辑

/**
 刷新数据

 @param model model
 */
- (void)reloadAuctionViewWith:(AuctionHomeModel *)model {
    _homeDataModel = model.data;
//    self.headerView.couponView.dataModel = model;
//    [self.headerView.couponView layoutSubviews];
    NSArray <AuctionHomeShopModel *>* shop = model.data.shop;
    self.headerView.recommendDatas = shop;
}



/**
 回调
 */
- (void)initBlock {
    SKWeakSelf;
#pragma mark -- mark CollectionViewBlock
    self.shareBlock = ^(NSIndexPath * _Nonnull indexPath) {
        // 分享按钮 // userInfo --> reg_num
        
    };
    
    self.selectBlock = ^(NSIndexPath * _Nonnull indexPath) {
        // collectionView cell 点击
        AuctionProductDetailVC *vc = [[AuctionProductDetailVC alloc] init];
        AuctionSellDataModel *model = weakSelf.colletionViewDelegate.dataArray[indexPath.item];
        vc.sellId = model.ID;
        vc.showType = AuctionProductDetailTypeDetail;
        [weakSelf.navigationController pushViewController:vc animated:true];
    };
    
    self.collectionCountDownEndBlock = ^{
      // 倒计时结束
        [weakSelf requestAuctionRecommandShopData];
    };
#pragma mark -- mark HeaderViewBlock
    self.bannerBlock = ^(NSInteger index) {
        // banner 点击事件
        
    };
    self.determineBlock = ^{
        // 鉴定详情按钮点击事件
        [weakSelf determineDetail];
    };
    self.btnsBlock = ^(NSInteger index) {
        // 四个按钮
        if (index == 0) {
            // 拍卖大厅
            [weakSelf auctionHall];
        }else if (index == 1) {
            // 精品拍场
            [weakSelf auctionTreasureHall];
        }else if (index == 2) {
            // 积分商城
            [weakSelf auctionScoreShop];
        }else if (index == 3) {
            // 成交记录
            [weakSelf dealList];
        }else { }
    };
    self.couponsProductButtonClickBlock = ^(NSInteger index) {
        // 优惠群商品
        if (weakSelf.homeDataModel) {
            NSArray <ProductDetailModel *>* goods = weakSelf.homeDataModel.goods;
            ProductDetailModel *ptModel1 = goods[index];
            ProductDetailVC *vc = [[ProductDetailVC alloc] init];
            vc.type = 0;
            vc.ptId = ptModel1.ptId;
            vc.showType = ProductDetailTypeDetail;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
    self.couponBlock = ^{
        if ([[UserInfoSingleton shareInstance].userInfo isLogin]) {
            // 优惠券
            AuctionCouponVC *vc = [[AuctionCouponVC alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:true];
        }else {
            [AppDelegate pushLoginView];
        }
    };
    self.recommendMoreBlock = ^{
        // 更多推荐
        [weakSelf auctionTreasureHall];
    };
    self.recommendSelectBlock = ^(NSIndexPath * _Nonnull indexPath) {
        // 推荐商品点击事件
        [weakSelf auctionTreasureHallWith:indexPath];
    };
}



#pragma mark -- mark 精品四按钮

/**
 拍卖大厅
 */
- (void)auctionHall {
    AuctionHallVC *vc = [[AuctionHallVC alloc] init];
    [self.navigationController pushViewController:vc animated:true];
}

/**
 精品拍场
 */
- (void)auctionTreasureHall {
    AuctionTreasureVC *vc = [[AuctionTreasureVC alloc] init];
    [self.navigationController pushViewController:vc animated:true];
}

/**
 精品拍场 店铺

 @param indexPath indexPath
 */
- (void)auctionTreasureHallWith:(NSIndexPath *)indexPath {
    AuctionHomeShopModel *model = self.headerView.recommandCellData[indexPath.section][indexPath.row];
    if (model.pass.length > 0) {
        SKWeakSelf;
        [WJPasswordView showPasswordView:^(NSString * _Nonnull password) {
            if ([password isEqualToString:model.pass]) {
                StoreHomePageVC *vc = [[StoreHomePageVC alloc] init];
                vc.shopId = model.ID;
                [weakSelf.navigationController pushViewController:vc animated:true];
            }else {
                [weakSelf showMessage:@"密码错误，请重试～"];
            }
        } CompleteHanlder:nil];
    }else {
        StoreHomePageVC *vc = [[StoreHomePageVC alloc] init];
        vc.shopId = model.ID;
        [self.navigationController pushViewController:vc animated:true];
    }
}

/**
 积分商城
 */
- (void)auctionScoreShop {
    if ([[UserInfoSingleton shareInstance].userInfo isLogin]) {
        AuctionSoreShopVC *vc = [[AuctionSoreShopVC alloc] init];
        [self.navigationController pushViewController:vc animated:true];
    }else {
        [AppDelegate pushLoginView];
    }
}

/**
 成交记录
 */
- (void)dealList {
    if ([[UserInfoSingleton shareInstance].userInfo isLogin]) {
        AuctionOrderListVC *vc = [[AuctionOrderListVC alloc] init];
        vc.isShowTabBar = false;
        vc.gk_navTitle = @"成交记录";
        [self.navigationController pushViewController:vc animated:true];
    }else {
        [AppDelegate pushLoginView];
    }
}

/**
 鉴定宝详情
 */
- (void)determineDetail {
//    http://hxapi.yupinyouxuan.com/index.php/Index/getNotice
    NSDictionary *param = @{@"type":@(10)};
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Index/getNotice" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        IndexNoticeModel *model = [IndexNoticeModel modelWithDictionary:response];
        if ([model isSuccess]) {
            NSArray <IndexNoticeInfoModel *>*datas = model.data;
            IndexNoticeInfoModel *info;
            for (IndexNoticeInfoModel *data in datas) {
                if ([data.type isEqualToString:@"10"]) {
                    // 鉴定宝
                    info = data;
                    break;
                }
            }
            if (info) {
                XMJSWebViewController * webVC = [[XMJSWebViewController alloc]init];
                webVC.type = WebType_H5_content;
                webVC.titleString = info.title;
                webVC.fileUrl = info.contents;
                [self.navigationController pushViewController:webVC animated:YES];
            }else {
                [weakSelf showMessage:@"暂无信息"];
            }
        }else {
            [weakSelf showMessage:model.msg];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}
@end
/*
"<p><img class=\"fr-dib fr-draggable\" src=\"http://apiadmin.yupinyouxuan.com/upload/news/2019_11_29/88cee6556402484aab34d19b8c29e8bd.jpg\" style=\"width: 100%;\"/><img class=\"fr-dib fr-draggable\" src=\"http://apiadmin.yupinyouxuan.com/upload/news/2019_11_29/3cd8309957421e7a6af08c8b07c60394.jpg\" style=\"width: 100%;\"/><img class=\"fr-dib fr-draggable\" src=\"http://apiadmin.yupinyouxuan.com/upload/news/2019_11_29/822ef739e1a3f21b1c70d11ebfc34190.jpg\" style=\"width: 100%;\"/><img class=\"fr-dib fr-draggable\" src=\"http://apiadmin.yupinyouxuan.com/upload/news/2019_11_29/4d83a8e588d353d067a1fb2b737bf345.jpg\" style=\"width: 100%;\"/></p>"
*/
/*
"<p><img class=\"fr-dib fr-draggable\" src=\"http://apiadmin.yupinyouxuan.com/upload/news/2019_11_29/dacfd6e669f2551862488d3147cece90.jpg\" style=\"width: 100%;\"/><img class=\"fr-dib fr-draggable\" src=\"http://apiadmin.yupinyouxuan.com/upload/news/2019_11_29/eaab6547679717f2c4e22671b5896ce2.jpg\" style=\"width: 100%;\"/><img class=\"fr-dib fr-draggable\" src=\"http://apiadmin.yupinyouxuan.com/upload/news/2019_11_29/b455492836f36d140d2b26882fd1cf5b.jpg\" style=\"width: 100%;\"/><img class=\"fr-dib fr-draggable\" src=\"http://apiadmin.yupinyouxuan.com/upload/news/2019_11_29/9891639c61685253ff2873c49c0b3033.jpg\" style=\"width: 100%;\"/></p>"*/
